using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace NeuroSpeech.Imap
{
	public class ImapResponseMessagePart : BaseImapResponse
	{

		public byte[] PartData { get; private set; }

		public string PartText { get; private set; }

		#region public override void  Process(ImapClient client)
		public override void Process(ImapClient client)
		{
			//base.Process(client);
			string line = client.ReadLine();
			//var tree = Parse(line + ")");

			//var tc1 = tree.GetChild(3);
			//tree = tc1.GetChild(2).GetChild(0);
			//int length = int.Parse(tree.Text);

			PartText = "";

			base.Process(client);

			if (Lines.Count > 1)
			{
				PartText = string.Join("\r\n", Lines.Take(Lines.Count - 1));
			}

		}
		#endregion


		#region public override void  PostProcess(ImapClient client)
		public override void PostProcess(ImapClient client)
		{
			string encoding = Part.Encoding.ToLower();
			switch (encoding)
			{
				case "base64":
					PartData = Convert.FromBase64String(PartText);
					PartText = null;
					break;
				case "7bit":
					break;
				case "quoted-printable":
					PartText = DecodeQuotedPrintable(PartText);
					break;
			}
		}
		#endregion


		private string DecodeQuotedPrintable(string input)
		{
			var occurences = new Regex(@"(=[0-9A-Z][0-9A-Z])+", RegexOptions.Multiline);
			var matches = occurences.Matches(input);
			foreach (Match m in matches)
			{
				byte[] bytes = new byte[m.Value.Length / 3];
				for (int i = 0; i < bytes.Length; i++)
				{
					string hex = m.Value.Substring(i * 3 + 1, 2);
					int iHex = Convert.ToInt32(hex, 16);
					bytes[i] = Convert.ToByte(iHex);
				}
				input = input.Replace(m.Value, Encoding.Default.GetString(bytes));
			}
			return input.Replace("=\r\n", "");
		}

		public ImapMimePart Part { get; set; }

		public string ResponseText
		{
			get
			{

				// decoded...
				return null;
			}
		}


	}
}
